<template>
  <div class="map-container">
    <div class="map-header" v-if="showSearch == true">
      <ElInput
        v-model="searchKeyword"
        placeholder="输入地点名称，如'天安门'"
        clearable
        @keydown.enter.prevent.native="handleSearch"
        @keyup.enter.prevent.native="handleSearch"
        class="search-input"
        @clear="handleClearSearch"
      >
      </ElInput>
      <el-button type="primary" @click="handleSearch" class="btn"
        >搜索</el-button
      >
    </div>
    <div id="map-container" ref="mapContainer"></div>

    <div class="search-results" v-show="searchResults.length > 0 || isLoading">
      <ElCard shadow="hover">
        <template #header>
          <div class="flex items-center justify-between">
            <h3>搜索结果</h3>
            <ElIcon v-if="isLoading" class="is-loading">
              <Loading />
            </ElIcon>
          </div>
        </template>
        <ElScrollbar height="300px">
          <template v-if="!isLoading">
            <div
              v-for="(item, index) in searchResults"
              :key="index"
              class="result-item"
              @click="centerToLocation(item)"
            >
              <div class="result-name">
                <ElIcon class="location-icon">
                  <Location />
                </ElIcon>
                {{ item.name }}
              </div>
              <div class="result-address">{{ item.address }}</div>
              <div class="result-distance" v-if="item.distance">
                <ElIcon>
                  <Position />
                </ElIcon>
                距离: {{ (item.distance / 1000).toFixed(1) }}公里
              </div>
            </div>
          </template>
          <div v-else class="loading-text">搜索中...</div>
        </ElScrollbar>
      </ElCard>
    </div>
  </div>
</template>
<script type="text/javascript">
// 必须在AMap JS加载前设置安全配置
window._AMapSecurityConfig = {
  securityJsCode: mapSetting.mapSecurity || '',
};
</script>
<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import {
  ElMessage,
  ElInput,
  ElButton,
  ElScrollbar,
  ElCard,
  ElIcon
} from 'element-plus';
import { mapSetting } from '#/api/map';
const props = defineProps({
  data: {
    type: Object,
    default: () => ({
      defaultAddress: '',
      defaultPoint: [],
    }),
  },
  showSearch: Boolean,
});
const emits = defineEmits(['getPosition']);

// 地图实例
const map = ref(null);
const mapContainer = ref(null);
const placeSearch = ref(null);
const marker = ref(null);
const markers = ref([]); // 存储所有标记的数组
const point = ref([]);
// 搜索相关
const searchKeyword = ref('');
const searchResults = ref([]);
const address = ref(''); // 地址
const maplist = ref([
  { x: '119.903124', y: '30.249647' },
  { x: '119.91061', y: '30.248632' },
]);

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: mapSetting.mapKey,
      version: '2.0',
      plugins: [
        'AMap.PlaceSearch',
        'AMap.Geocoder',
        'AMap.AutoComplete',
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.Marker',
        'AMap.Geolocation',
      ],
    });

    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      zoom: 13,
      center: [116.397428, 39.90923], // 默认北京中心点
      viewMode: '2D',
      layers: [new AMap.TileLayer.Satellite()],
    });
    // 初始化地点搜索
    placeSearch.value = new AMap.PlaceSearch({
      map: map.value,
      pageSize: 10,
      pageIndex: 1,
      city: '全国',
    });
    // 添加定位控件
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      buttonPosition: 'RB',
    });
    map.value.addControl(geolocation);

    // 添加标记
    addWarningCircles(AMap);
    // 地图点击事件
    map.value.on('click', clickMapHandler);
  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

const isLoading = ref(false);

const handleClearSearch = () => {
  searchResults.value = [];
  searchKeyword.value = '';
  isLoading.value = false;
};

// 执行搜索
const handleSearch = () => {
  const keyword = searchKeyword.value.trim();
  if (!keyword) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }

  isLoading.value = true;
  searchResults.value = [];

  placeSearch.value.search(keyword, (status, result) => {
    isLoading.value = false;

    if (status === 'complete' && result.poiList?.pois) {
      searchResults.value = result.poiList.pois;
      if (searchResults.value.length === 0) {
        ElMessage.info('未找到相关地点');
      }
    } else {
      const errorMsg = result?.info || '搜索失败';
      ElMessage.error(errorMsg);
      console.error('搜索出错:', errorMsg);
      searchResults.value = [];
    }
  });
};

// 定位到指定位置
const centerToLocation = (poi) => {
  searchResults.value = [];
  isLoading.value = false;
  if (!map.value) return;

  // 清除旧标记
  if (marker.value) {
    map.value.remove(marker.value);
  }

  // 创建新标记
  marker.value = new AMap.Marker({
    position: [poi.location.lng, poi.location.lat],
    map: map.value,
  });

  // 移动地图中心点
  map.value.setCenter([poi.location.lng, poi.location.lat]);
  map.value.setZoom(15);

  searchKeyword.value = poi.name;
  emits('getPosition', {
    defaultAddress: poi.name,
    defaultPoint: [poi.location.lng, poi.location.lat],
  });
};

// 增加点标记
const addMarker = () => {
  // 清除其他icon
  if (marker.value) {
    marker.value.setMap(null);
    marker.value = null;
  }
  // 重新渲染icon
  marker.value = new AMap.Marker({
    position: point.value, // icon经纬度
    offset: new AMap.Pixel(-13, -30), // icon中心点的偏移量
    icon: new AMap.Icon({
      image:
        '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
      size: new AMap.Size(30, 40), // 图标大小
      imageSize: new AMap.Size(30, 40),
    }),
  });
  marker.value.setMap(map.value); // 设置icon
};

// 将经纬度转换为地址
const getAddress = () => {
  geocoder.value.getAddress(point.value, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      address.value = result.regeocode.formattedAddress;
      emits('getPosition', {
        defaultAddress: result.regeocode.formattedAddress,
        defaultPoint: point.value,
      });
    } else {
      let errorMsg = '地理编码失败';
      if (result?.info === 'INVALID_USER_KEY') {
        errorMsg = '高德地图API密钥无效，请检查配置';
      } else if (result?.info === 'DAILY_QUERY_OVER_LIMIT') {
        errorMsg = '高德地图API调用已达日限额';
      }
      ElMessage.error(errorMsg);
      console.error('地理编码失败', result);
    }
  });
};

const clickMapHandler = (e) => {
  const lng = e.lnglat.lng;
  const lat = e.lnglat.lat;
  point.value = [lng, lat];
  map.value?.setCenter(point.value);
  // 增加点标记
  addMarker();
  getAddress();
};

// 添加圆形警告区域
const addWarningCircles = (AMap) => {
  // 清除所有现有标记和圆形
  clearAllMarkers();

  maplist.value.forEach((item) => {
    // 创建圆形覆盖物
    const circle = new AMap.Circle({
      center: [parseFloat(item.x), parseFloat(item.y)], // 圆心坐标
      radius: 200, // 半径（单位：米）
      strokeColor: '#fff', // 边框颜色（红色）
      strokeOpacity: 0.8, // 边框透明度
      strokeWeight: 2, // 边框宽度
      fillColor: '#00bcd4', // 填充颜色（红色）
      fillOpacity: 0.3, // 填充透明度
      zIndex: 10, // 层级
    });

    // 添加到地图
    circle.setMap(map.value);

    // 可以添加点击事件
    circle.on('click', () => {
      console.log('点击了圆形警告区域:', item);
    });

    markers.value.push(circle); // 存储以便后续清除
  });

  // 调整地图视野以显示所有圆形
  if (maplist.value.length > 0) {
    map.value.setFitView();
  }
};
// 清除所有标记
const clearAllMarkers = () => {
  if (markers.value.length > 0) {
    map.value.remove(markers.value);
    markers.value = [];
  }
};
// 生命周期
onMounted(() => {
  initMap();
});

onBeforeUnmount(() => {
  // 清理地图
  if (map.value) {
    map.value.destroy();
  }
});
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 500px;
}

#map-container {
  width: 100%;
  height: 100%;
}

.map-header {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  display: flex;
  width: 400px;
}

.search-input {
  margin-right: 10px;

  :deep(.el-input__wrapper) {
    color: #303133;
    border-radius: 4px;
  }

  /* box-shadow: 0 2px 6px rgb(0 0 0 / 30%); */
}

.btn {
  font-size: 12px !important;
  font-weight: 400 !important;
  color: #fff !important;
}

.search-results {
  position: absolute;
  top: 80px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.result-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-name {
  margin-bottom: 5px;
  font-weight: bold;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.result-distance {
  margin-top: 5px;
  font-size: 12px;
  color: #409eff;
}
</style>
